package com.android.example.app3;

import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.bumptech.glide.Glide;

public class MainActivity2 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main2);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        ImageView fullScreenImage = findViewById(R.id.image_view);
        // 从Intent中获取图片路径
        // 获取传递的图片Uri
        Uri imageUri = getIntent().getParcelableExtra("image_uri");
        // 使用Glide加载Uri指向的图片
        if (imageUri != null) {
            Glide.with(this)
                    .load(imageUri)
                    .into(fullScreenImage);
        } else {
            Toast.makeText(MainActivity2.this, "照片imageUri获取失败.", Toast.LENGTH_SHORT).show();
        }
        fullScreenImage.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(imageUri, "image/*");
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivity(intent);
        });
        fullScreenImage.setOnLongClickListener(v -> {
            String filePath = getRealPathFromUri(this, imageUri);
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("image/*");
            shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
            startActivity(Intent.createChooser(shareIntent, "分享到"));
            return true; // Return true to indicate the event has been consumed
        });
    }


    public String getRealPathFromUri(Context context, Uri uri) {
        String filePath = "";
        try {
            if (DocumentsContract.isDocumentUri(context, uri)) {
                // 如果是KitKat及以上版本，且Uri是DocumentsProvider类型的
                String docId = DocumentsContract.getDocumentId(uri);
                if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                    // 来自媒体文档
                    String id = docId.split(":")[1];
                    String selection = MediaStore.Images.Media._ID + "=" + id;
                    filePath = queryImagePath(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
                } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                    // 来自下载文档
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.parseLong(docId));
                    filePath = queryImagePath(context, contentUri, null);
                } else if ("content".equalsIgnoreCase(uri.getScheme())) {
                    // 其他情况下的content:// Uri
                    filePath = queryImagePath(context, uri, null);
                }
            } else if ("content".equalsIgnoreCase(uri.getScheme())) {
                // 低于KitKat版本的content:// Uri
                filePath = queryImagePath(context, uri, null);
            } else if ("file".equalsIgnoreCase(uri.getScheme())) {
                // 文件路径Uri
                filePath = uri.getPath();
            }
        } catch (Exception e) {
            Log.e("ImageUtils", "Error getting real path from URI: ", e);
        }
        return filePath;
    }

    private String queryImagePath(Context context, Uri uri, String selection) {
        Cursor cursor = null;
        String column = MediaStore.Images.Media.DATA;
        String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return "";
    }


    // 处理屏幕旋转等配置变化（可选）
    @Override
    protected void onResume() {
        super.onResume();

    }

}